/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.anden.panningview;

import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.Component;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * PanningAnimatorValue
 */
public class PanningAnimatorValue extends AnimatorValue implements Animator.StateChangedListener {
    private WeakReference<Component> targetComponent;
    private ArrayList<AnimatorParamsEntity> valueSet;
    private static final int DEFAULT_DURATION = 1000;
    private long mDuration = DEFAULT_DURATION;
    private int mAnimatorType = -1;
    private int unitTime = 0;
    private AnimatorProperty runningAnimator;
    private int runningIndex = 0;

    private PanningAnimatorValue(Component component, int animatorType,
                                 long duration, List<AnimatorParamsEntity> values) throws Exception {
        if (!AnimatorTypes.checkAnimatorType(animatorType)) {
            LogUtil.debug("AnimatorTypes", "animationType");
        }
        if (duration <= 0) {
            LogUtil.debug("Duration", "must be greater than zero");
        }
        mDuration = duration;
        unitTime = Math.round(duration / values.size());
        targetComponent = new WeakReference<>(component);
        mAnimatorType = animatorType;
        valueSet = new ArrayList<>(values);
        setDuration(duration);
        setStateChangedListener(this);
    }

    private void configAnimator() {
        if (runningIndex < valueSet.size()) {
            runningAnimator = AnimationFactory.genAnimatorByType(targetComponent.get(),
                    mAnimatorType, valueSet.get(runningIndex), unitTime, 0, this);
            if (runningAnimator != null) {
                runningAnimator.start();
            }
        }
    }

    @Override
    public void start() {
        configAnimator();
    }

    @Override
    public void onStart(Animator animator) {
    }

    @Override
    public void onStop(Animator animator) {
    }

    @Override
    public void onCancel(Animator animator) {
    }

    @Override
    public void onEnd(Animator animator) {
        runningIndex++;
        configAnimator();
    }

    @Override
    public void onPause(Animator animator) {
    }

    @Override
    public void onResume(Animator animator) {
    }
}